package com.lx.controller;

import com.lx.bean.Brand;
import com.lx.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    @GetMapping("/brands")
    public Map showPageBrand(@RequestParam(value = "page",defaultValue = "1") Integer page, @RequestParam(value = "limit",defaultValue = "5") Integer limit){
        List<Brand> brands = brandService.showPageBrand(page,limit);
        long count = brandService.getCount(page,limit);
        Map map = new HashMap();
        map.put("code",0);
        map.put("count",count);
        map.put("data",brands);
        for (Brand brand : brands) {
            System.err.println(brand);
        }
        System.err.println("count = " + count);
        return map;
    }
    @RequestMapping("/upload")
    public Map upload(MultipartFile file, HttpServletRequest req){
        String realPath = req.getRealPath("/img/brandImg/");
        String fileName = file.getOriginalFilename();//获取文件名
        Map map = new HashMap();
        try(
                InputStream in = file.getInputStream();//获取文件的输入流
                OutputStream out = new FileOutputStream(realPath + fileName);//输出文件到目标文件夹
        ){
            FileCopyUtils.copy(in,out);
            map.put("status", "success");
            map.put("path", fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    @PostMapping("/brands")
    public Map addBrand(@RequestBody Brand brand){
        brandService.addBrand(brand);
        return new HashMap(){
            {put("status","success");}
        };
    }
    @DeleteMapping("/brands/{id}")
    public Map removeBrand(@PathVariable("id") Integer id){
        brandService.removeBrand(id);
        return new HashMap(){
            {put("status","success");}
        };
    }
    @PutMapping("/brands")
    public Map updateBrand(@RequestBody Brand brand){
        brandService.modifyBrand(brand);
        return new HashMap(){
            {put("status","success");}
        };
    }
}
